FROM node:18-alpine AS builder

WORKDIR /usr/src/app

# Copy package.json files
COPY package*.json ./

# Install all dependencies and NestJS CLI globally
RUN npm ci && \
    npm install -g @nestjs/cli

# Copy source code
COPY . .

# Build the application
RUN npm run build

# Install production dependencies
RUN npm prune --production

# Use Alpine-based Node.js image for production
FROM node:18-alpine

# Accept build arguments for environment configuration
ARG NODE_ENV=production
ARG GITHUB_REPOSITORY
ARG ENVIRONMENT=test
ARG MAX_MEMORY_RESTART=8G

# Set environment variables
ENV NODE_ENV=${NODE_ENV}
ENV ENVIRONMENT=${ENVIRONMENT}
ENV PATH=/usr/src/app/node_modules/.bin:$PATH
ENV MAX_MEMORY_RESTART=${MAX_MEMORY_RESTART}

WORKDIR /usr/src/app

# Copy package.json files
COPY package*.json ./

# Copy node_modules from builder stage
COPY --from=builder /usr/src/app/node_modules ./node_modules

# Install PM2 globally in the production image with a specific version
RUN npm install -g pm2@5.4.3

# Install dependencies required for argon2
RUN apk add --no-cache make gcc g++ python3

# Create logs directory for PM2
RUN mkdir -p logs && chmod -R 777 logs

# Copy built application from builder stage
COPY --from=builder /usr/src/app/dist ./dist

# Copy development scripts
COPY scripts/dev ./scripts/dev

# Copy PM2 configuration
COPY ecosystem.config.js ./

# Copy .env file if it exists (created during CI/CD)
COPY .env* ./

EXPOSE 3000

# Use PM2 to start the application
CMD ["pm2-runtime", "ecosystem.config.js"]